package com.gcloud.controller.network.handler.api.subnet.standard;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.gcloud.controller.ResourceIsolationCheck;
import com.gcloud.controller.enums.ResourceIsolationCheckType;
import com.gcloud.controller.network.model.DescribeVSwitchesParams;
import com.gcloud.controller.network.service.ISwitchService;
import com.gcloud.controller.utils.ApiUtil;
import com.gcloud.core.exception.GCloudException;
import com.gcloud.core.handle.ApiHandler;
import com.gcloud.core.handle.MessageHandler;
import com.gcloud.core.util.BeanUtil;
import com.gcloud.framework.db.PageResult;
import com.gcloud.header.ApiVersion;
import com.gcloud.header.Module;
import com.gcloud.header.SubModule;
import com.gcloud.header.network.model.VSwitchSetType;
import com.gcloud.header.network.model.standard.StandardVSwitchSetType;
import com.gcloud.header.network.msg.api.standard.StandardApiDescribeVSwitchesMsg;
import com.gcloud.header.network.msg.api.standard.StandardApiDescribeVSwitchesReplyMsg;

@ApiHandler(module=Module.ECS,subModule=SubModule.VSWITCH,action="DescribeVSwitches", versions = {ApiVersion.Standard})
@ResourceIsolationCheck(resourceIsolationCheckType = ResourceIsolationCheckType.ROUTER, resourceIdField = "vpcId")
public class StandardApiDescribeVSwitchesHandler extends MessageHandler<StandardApiDescribeVSwitchesMsg, StandardApiDescribeVSwitchesReplyMsg>{

	@Autowired
	private ISwitchService subnetService;
	
	@Override
	public StandardApiDescribeVSwitchesReplyMsg handle(StandardApiDescribeVSwitchesMsg msg) throws GCloudException {
		DescribeVSwitchesParams params = BeanUtil.copyProperties(msg, DescribeVSwitchesParams.class);
		
		PageResult<VSwitchSetType> response = subnetService.describeVSwitches(params, msg.getCurrentUser());
		PageResult<StandardVSwitchSetType> stdResponse = ApiUtil.toPage(response, toStandardReply(response.getList()));
		
		StandardApiDescribeVSwitchesReplyMsg replyMsg = new StandardApiDescribeVSwitchesReplyMsg();
        replyMsg.init(stdResponse);
        return replyMsg;
	}
	
	private List<StandardVSwitchSetType> toStandardReply(List<VSwitchSetType> list) {
		if(null == list) {
			return null;
		}
		
		List<StandardVSwitchSetType> stdList = new ArrayList<>();
		
		for (VSwitchSetType item : list) {
			StandardVSwitchSetType tmp = BeanUtil.copyProperties(item, StandardVSwitchSetType.class);
			stdList.add(tmp);
		}
		return stdList;
	}

}
